<template>
  <div class="l-rblock">
    <div v-show="steps(0)" class="l-rblock" style="padding: 24px">
      <div class="l-page-panel">
        <el-form :model="formData" :rules="rules" size="mini" ref="baseInfo" label-width="72px">
          <el-col :span="24">
            <el-form-item label="名称" prop="f_Name">
              <el-input v-model="formData.f_Name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类" prop="f_Category">
              <l-tree-select
                v-model="formData.f_Category"
                placeholder="请选择"
                :options="lr_dataItemTree(lr_dataItem['FormSort'])"
              >
              </l-tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="formData.f_FormType != 2" label="数据库" prop="f_DbCode">
              <el-select v-model="formData.f_DbCode" placeholder="请选择">
                <el-option-group v-for="group in lr_dblinkTree" :key="group.id" :label="group.label">
                  <el-option v-for="item in group.children" :key="item.id" :label="item.label" :value="item.id">
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="f_EnabledMark">
              <el-switch :active-value="1" :inactive-value="0" v-model="formData.f_EnabledMark"> </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类型" prop="f_FormType">
              <l-radio
                :options="[
                  { value: 0, label: '常规表单' },
                  { value: 1, label: '视图表单' },
                  { value: 2, label: '接口模式' },
                ]"
                v-model="formData.f_FormType"
                @change="handleFormTypeChange"
              >
              </l-radio>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="f_Description">
              <el-input type="textarea" v-model="formData.f_Description"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
        <template v-if="formData.f_FormType == 0">
          <el-col :span="24">
            <div class="l-title">添加数据库表（请先选择数据库）</div>
          </el-col>
          <el-col :key="1" :span="24">
            <l-edit-table addBtnText="添加" :dataSource="dbTableData" @addRow="addRow" @deleteRow="deleteRow">
              <el-table-column prop="type" label="类别" width="64" align="center">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.type == 'main'" size="mini">主表</el-tag>
                  <el-tag @click="chlidTagClick(scope.row)" v-else size="mini" style="cursor: pointer" type="warning"
                    >子表</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column prop="name" label="表名" minWidth="100"> </el-table-column>
              <el-table-column prop="field" label="外键" minWidth="100">
                <template v-if="scope.row.type != 'main'" slot-scope="scope">
                  <el-select size="mini" v-model="scope.row.field" placeholder="请选择">
                    <el-option
                      v-for="item in scope.row.columns || []"
                      :key="item.name"
                      :label="item.name"
                      :value="item.name"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="relationName" label="关联表" minWidth="100">
                <template v-if="scope.row.type != 'main'" slot-scope="scope">
                  <el-select size="mini" v-model="scope.row.relationName" placeholder="请选择">
                    <el-option
                      v-for="item in relationTables(scope.row.name)"
                      :key="item.name"
                      :label="item.name"
                      :value="item.name"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="relationField" label="关联主键" minWidth="100">
                <template v-if="scope.row.type != 'main' && scope.row.relationName" slot-scope="scope">
                  <el-select size="mini" v-model="scope.row.relationField" placeholder="请选择">
                    <el-option
                      v-for="item in relationTableFields(scope.row.relationName)"
                      :key="item.name"
                      :label="item.name"
                      :value="item.name"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
            </l-edit-table>
          </el-col>
          <el-col :span="24">
            <div class="l-title">添加数据库关联表，只用来做数据权限设置（请先选择数据库）</div>
          </el-col>
          <el-col :key="2" :span="24">
            <l-edit-table
              addBtnText="添加"
              :dataSource="dbTableRData"
              @addRow="addDbTableRData"
              @deleteRow="deleteDbTableRData"
            >
              <el-table-column prop="fname" label="名称" minWidth="160">
                <template slot-scope="scope">
                  <el-input size="mini" v-model="scope.row.fname"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="表名" minWidth="160"> </el-table-column>
              <el-table-column prop="cfield" label="比较字段" minWidth="160">
                <template slot-scope="scope">
                  <el-select size="mini" v-model="scope.row.cfield" placeholder="请选择">
                    <el-option
                      v-for="item in scope.row.columns || []"
                      :key="item.name"
                      :label="item.name"
                      :value="item.name"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="field" label="外键" minWidth="160">
                <template slot-scope="scope">
                  <el-select size="mini" v-model="scope.row.field" placeholder="请选择">
                    <el-option
                      v-for="item in scope.row.columns || []"
                      :key="item.name"
                      :label="item.name"
                      :value="item.name"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="relationName" label="关联表" minWidth="160">
                <template v-if="scope.row.type != 'main'" slot-scope="scope">
                  <el-select size="mini" v-model="scope.row.relationName" placeholder="请选择">
                    <el-option v-for="item in dbTableData" :key="item.name" :label="item.name" :value="item.name">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="relationField" label="关联主键" minWidth="160">
                <template v-if="scope.row.relationName" slot-scope="scope">
                  <el-select size="mini" v-model="scope.row.relationField" placeholder="请选择">
                    <el-option
                      v-for="item in relationTableFields(scope.row.relationName)"
                      :key="item.name"
                      :label="item.name"
                      :value="item.name"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
            </l-edit-table>
          </el-col>
        </template>
        <template v-if="formData.f_FormType == 1">
          <el-col :span="24">
            <div class="l-title">添加数据视图（请先选择数据库）</div>
          </el-col>
          <el-col :span="24">
            <l-edit-table addBtnText="添加" :dataSource="dbTableData" @addRow="addSqlData" @deleteRow="deleteSqlData">
              <el-table-column prop="type" label="类别" width="64" align="center">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.type == 'main'" size="mini">主</el-tag>
                  <el-tag v-else size="mini" type="warning">子</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="名称" minWidth="160">
                <el-button type="text" slot-scope="scope" @click.stop="editSqlData(scope.row)">{{
                  scope.row.name
                }}</el-button>
              </el-table-column>
              <el-table-column prop="relationField" label="关联字段" minWidth="160">
                <el-select
                  v-if="scope.row.type != 'main'"
                  slot-scope="scope"
                  size="mini"
                  v-model="scope.row.relationField"
                  placeholder="请选择"
                >
                  <el-option v-for="item in sqlMainCols || []" :key="item.name" :label="item.name" :value="item.name">
                  </el-option>
                </el-select>
              </el-table-column>
            </l-edit-table>
          </el-col>
        </template>

        <template v-if="formData.f_FormType == 2">
          <el-col :span="24">
            <div class="l-title">添加接口（请先选择接口）</div>
          </el-col>
          <el-col :span="24">
            <l-edit-table
              addBtnText="添加"
              :dataSource="dbTableData"
              @addRow="showApiForm"
              :columns="lr_getPageColumns(columns)"
              @deleteRow="deleteApiData"
            >
              <template v-slot:f_RequestMethod="scope">
                <el-tag type="success">{{ scope.row.f_RequestMethod }}</el-tag>
              </template>
              <template v-slot:apiType="scope">
                <el-tag type="success">{{ getApiType(scope.row.apiType) }}</el-tag>
              </template>
            </l-edit-table>
          </el-col>
        </template>
      </div>
    </div>
    <div v-show="steps(1)" class="l-rblock">
      <l-form-design :dbTables="getDesignDbTables" ref="formDesign"></l-form-design>
    </div>

    <div v-show="steps(2)" class="l-rblock" style="padding: 24px">
      <apiOutput ref="apiOutput"></apiOutput>
    </div>

    <l-codetable-selectdialog
      :visible.sync="dbtableSelectdialog"
      :dbCode="formData.f_DbCode"
      :isOkClose="false"
      @select="dbSelect"
    >
    </l-codetable-selectdialog>

    <!--对话框-->
    <l-dialog
      :title="sqlDialogTitle"
      :visible.sync="addSqlDialog"
      :width="640"
      @ok="sqlDialogSave"
      @closed="sqlDialogClosed"
      @opened="sqlDialogOpened"
    >
      <sql-form ref="sqlForm"></sql-form>
    </l-dialog>
    <!--对话框 end-->

    <!--对话框-->
    <l-dialog
      title="选择接口"
      :visible.sync="apiDialog"
      :width="1200"
      :height="600"
      @closed="hideApiForm"
      @ok="hideApiForm"
    >
      <api-form ref="apiForm" @childForm="childFormChange"></api-form>
    </l-dialog>
    <!--对话框 end-->

    <l-dialog
      class="ui-dialog-pop"
      data-center="true"
      title="接口类型"
      :center="true"
      :width="400"
      :height="200"
      :visible.sync="dialogTypeVisible"
      :modal-append-to-body="false"
    >
      <template>
        <div class="ui-dialog-TipText">
          <span>请选择你的接口类型</span>
        </div>
        <div class="dialog-footer">
          <el-button type="primary" plain @click="apiSelectChange(0)">首页</el-button>
          <el-button type="primary" plain @click="apiSelectChange(1)">查</el-button>
          <el-button type="primary" plain @click="apiSelectChange(2)">增</el-button>
          <el-button type="primary" plain @click="apiSelectChange(3)">改</el-button>
          <el-button type="primary" plain @click="apiSelectChange(4)">删</el-button>
        </div>
      </template>
    </l-dialog>
  </div>
</template>
<script>
const apiScheme = window.$api.custmerForm.scheme;
const apiCodeTable = window.$api.data.codeTable;

import SqlForm from "./sqlForm.vue";
import apiForm from "./apiForm.vue";
import apiOutput from "./apiOutput";
//import testData from './postData.js'

export default {
  props: {
    stepActive: {
      type: Number,
      default: 0,
    },
  },
  components: {
    SqlForm,
    apiForm,
    apiOutput,
  },
  data() {
    return {
      formData: {
        f_Name: "",
        f_Category: "",
        f_DbCode: "",
        f_EnabledMark: 1,
        f_FormType: 0,
        f_Description: "",
      },
      rules: {
        f_Name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        f_Category: [{ required: true, message: "请选择分类", trigger: "change" }],
        f_DbCode: [{ required: true, message: "请选择数据库", trigger: "change" }],
      },
      dbTableData: [],
      dbtableSelectdialog: false,

      dbTableRData: [], // 关联表数据用于数据权限
      isAddDbTableRData: false,

      addSqlDialog: false,
      editSql: false,
      sqlDialogTitle: "",
      sqlDialogRow: null,

      isNotFetchTables: false,
      tableColumns: {}, // 缓存列信息

      //接口数据
      apiDialog: false,
      apiTableData: [],
      columns: [
        { label: "接口名称", prop: "f_Name", minWidth: "120" },
        { label: "接口地址", prop: "f_Url", minWidth: "240" },
        // {label:'数据结构',prop:'Type',minWidth:'120'},
        { label: "请求类型", prop: "f_RequestMethod", minWidth: "120" },
        { label: "接口类型", prop: "apiType", minWidth: "120" },
      ],
      dialogTypeVisible: false,
      dialogApiData: {},
      requstType: ["get", "post", "put", "delete"],
      scheme: {},
      designDbTables: [],
    };
  },
  created() {
    this.initData();
    //this.$store.commit('f_FormType',0);
  },
  computed: {
    sqlMainCols() {
      const table = this.dbTableData.find((t) => t.type == "main");
      return table.columns;
    },
    getDesignDbTables() {
      if (this.formData.f_FormType == 2) {
        return this.designDbTables;
      } else {
        return this.dbTableData;
      }
    },
  },
  watch: {
    stepActive(val) {
      if (val == 2) {
        this.$refs.apiOutput.setFormDesign(this.$refs.formDesign.getData());
      }
    },
  },
  methods: {
    getApiType(type) {
      switch (type) {
        case 0:
          return "首页";
        case 1:
          return "查";
        case 2:
          return "增";
        case 3:
          return "改";
        case 4:
          return "删";
      }
    },
    initData() {
      this.lr_loadDblink();
    },

    //数据库选择
    async dbSelect(list, showLoading, hideLoading) {
      showLoading();
      const tableList = [];
      const notAddTable = [];
      list.forEach((item) => {
        const table = { id: item.f_TableName, name: item.f_TableName, comment: item.f_Description, columns: [] };

        // 加载表的列信息
        if (this.tableColumns[table.name]) {
          table.columns = this.tableColumns[table.name];
        } else {
          tableList.push(table);
        }
        if (this.isAddDbTableRData) {
          if (
            this.dbTableData.find((t) => {
              return t.name == table.name;
            }) == undefined
          ) {
            this.dbTableRData.push(table);
          } else {
            notAddTable.push(table.name);
          }
        } else {
          if (this.dbTableData.length == 0) {
            table.type = "main";
            this.dbTableData.push(table);
          } else if (
            this.dbTableData.find((t) => {
              return t.name == table.name;
            }) == undefined
          ) {
            table.type = "chlid";
            this.dbTableData.push(table);
          } else {
            notAddTable.push(table.name);
          }
        }
      });

      if (tableList.length > 0) {
        const codeTables = await this.$awaitWraper(
          apiCodeTable.getList(this.formData.f_DbCode, String(tableList.map((t) => t.name)))
        );
        for (const tableItem of tableList) {
          const codeTable = codeTables.find((t) => t.lr_db_codetableEntity.f_TableName == tableItem.name);
          tableItem.columns = codeTable.lr_db_codecolumnsList.map((t) => ({
            name: t.f_DbColumnName,
            csType: t.f_CsType,
            isIdentity: t.f_IsIdentity == 1,
            isPrimary: t.f_IsPrimaryKey == 1,
            isNullable: t.f_IsNullable == 1,
            coment: t.f_Description,
          }));

          this.tableColumns[tableItem.name] = tableItem.columns;
        }
      }

      if (notAddTable.length > 0) {
        if (this.isAddDbTableRData) {
          this.$message({
            message: `不能是表单已经绑定的表【${String(notAddTable)}】`,
            type: "warning",
          });
        } else {
          this.$message({
            message: `重复添加表【${String(notAddTable)}】`,
            type: "warning",
          });
        }
      }

      this.dbtableSelectdialog = false;
      //console.log(this.dbTableData);
      hideLoading();
    },
    chlidTagClick(row) {
      this.dbTableData.find((t) => {
        return t.type == "main";
      }).type = "chlid";
      row.type = "main";
      this.$set(this.dbTableData, 0, this.dbTableData[0]);
    },
    addRow() {
      this.isAddDbTableRData = false;
      if (this.formData.f_DbCode) {
        this.dbtableSelectdialog = true;
      } else {
        this.$message({
          message: "请选择数据库",
          type: "warning",
        });
      }
    },
    deleteRow(data) {
      this.dbTableData.splice(data.index, 1);
      if (data.row.type == "main" && this.dbTableData.length > 0) {
        this.dbTableData[0].type = "main";
        this.$set(this.dbTableData, 0, this.dbTableData[0]);
      }
    },
    relationTables(myName) {
      let list = [];
      this.dbTableData.forEach((item) => {
        if (item.name != myName) {
          list.push(item);
        }
      });
      return list;
    },
    relationTableFields(tableName) {
      const table =
        this.dbTableData.find((t) => {
          return t.name == tableName;
        }) || {};
      return table.columns || [];
    },

    addDbTableRData() {
      this.isAddDbTableRData = true;
      if (this.formData.f_DbCode) {
        this.dbtableSelectdialog = true;
      } else {
        this.$message({
          message: "请选择数据库",
          type: "warning",
        });
      }
    },
    deleteDbTableRData(data) {
      this.dbTableRData.splice(data.index, 1);
    },

    validateSteps() {
      return new Promise((resolve) => {
        if (this.stepActive == 0) {
          // 判断基础信息是否填写完整
          this.validateBaseInfo().then((res) => {
            resolve(res);
          });
        } else {
          resolve(true);
        }
      });
    },
    steps(num) {
      return this.stepActive == num;
    },

    //表单验证
    validateBaseInfo() {
      return new Promise((resolve) => {
        this.$refs.baseInfo.validate((valid) => {
          if (valid) {
            if (this.formData.f_FormType == 2) {
              if (!this.checkNextAllDbTableData()) {
                this.$message({
                  type: "error",
                  message: "四种接口类型都为必填!",
                });
                resolve(false);
                return;
              }
              this.$refs.apiOutput.setFormData(this.dbTableData, this.scheme, this.designDbTables);
              resolve(true);
              return;
            }

            if (this.isNotFetchTables) {
              this.$message({
                type: "error",
                message: "请将数据表的对象导入,点击数据表添加按钮,导入表重新编辑页面!",
              });
              resolve(false);
              return;
            }

            if (this.dbTableData.length > 0) {
              if (this.formData.f_FormType == 0) {
                if (
                  this.dbTableData.find(
                    (t) =>
                      t.type != "main" &&
                      (this.$validatenull(t.field) ||
                        this.$validatenull(t.relationName) ||
                        this.$validatenull(t.relationField))
                  ) != undefined
                ) {
                  this.$message({
                    type: "error",
                    message: "请完善数据库表信息!",
                  });
                  resolve(false);
                  return;
                }
              } else {
                if (
                  this.dbTableData.find((t) => t.type != "main" && this.$validatenull(t.relationField)) != undefined
                ) {
                  this.$message({
                    type: "error",
                    message: "请完善子视图和主视图关联!",
                  });
                  resolve(false);
                  return;
                }
              }
            } else {
              if (this.formData.f_FormType != 2) {
                this.$message({
                  type: "error",
                  message: this.formData.f_FormType != 1 ? "请添加数据库表!" : "请添加视图语句",
                });
              }
              resolve(false);
              return;
            }

            if (this.dbTableRData.length > 0) {
              if (
                this.dbTableRData.find(
                  (t) =>
                    this.$validatenull(t.fname) ||
                    this.$validatenull(t.cfield) ||
                    this.$validatenull(t.field) ||
                    this.$validatenull(t.relationName) ||
                    this.$validatenull(t.relationField)
                ) != undefined
              ) {
                this.$message({
                  type: "error",
                  message: "请完善数据库关联表信息!",
                });
                resolve(false);
                return;
              }
            }

            this.$nextTick(() => {
              this.$refs.formDesign.updateTable();
            });

            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
    resetForm() {
      this.$refs.formDesign.clear();
      this.$formClear(this.$refs.baseInfo);
      this.isNotFetchTables = false;
      this.dbTableData = [];
      this.dbTableRData = [];
      this.tableColumns = {};
      this.designDbTables = [];
    },
    validateForm() {
      return this.$refs.formDesign.validate();
    },

    //编辑-数据设置
    async setForm(id) {
      //console.log("当前接口"+id);

      const data = await this.$awaitWraper(apiScheme.get(id));

      if (data) {
        let scheme = JSON.parse(data.scheme.f_Scheme);
        this.scheme = scheme;
        //let scheme=testData.schemeData();
        //console.log('scheme',scheme);
        data.info.f_DbCode = scheme.dbCode;
        this.formData = data.info;

        this.dbTableData = scheme.db;
        this.designDbTables = scheme.designDbTables || [];
        this.dbTableRData = scheme.rdb || [];
        this.$refs.formDesign.setFormType(this.formData.f_FormType);
        this.$emit("setFormType", this.formData.f_FormType);
        if (this.formData.f_FormType == 2) {
          let paramIds = scheme.db.map((item) => item.f_Id).join(",");
          const dbTableData = await this.$awaitWraper(
            apiScheme.apiParams(`${this.apiUrl}data/dataInterface/entitysbyids/${paramIds}`, "get")
          );
          if (dbTableData) {
            this.dbTableData = dbTableData.map((item) => {
              const db = scheme.db.find((t) => item.f_Id == t.f_Id);
              if (db) {
                return {
                  ...item,
                  apiType: db.apiType,
                };
              } else {
                return item;
              }
            });
          }

          this.$refs.apiOutput.setFormData(this.dbTableData, scheme, this.designDbTables); //接口输出数据
        } else if (this.formData.f_FormType == 0) {
          const tableNames = [];
          tableNames.push(...this.dbTableData.map((t) => t.name));
          tableNames.push(...this.dbTableRData.map((t) => t.name));

          // 加载表数据
          const codeTables = await this.$awaitWraper(apiCodeTable.getList(scheme.dbCode, String(tableNames)));
          // 新版本加入数据模型这个概念，表单设计模版里不保存列的信息
          // 当数据对象被改变时会直接影响到表单
          if (codeTables.length < tableNames.length) {
            // 表示部分数据表没有加载到，需要导入或添加
            this.isNotFetchTables = true;
          } else {
            const tableList = [...this.dbTableData, ...this.dbTableRData];
            for (const table of tableList) {
              const codeTable = codeTables.find((t) => t.lr_db_codetableEntity.f_TableName == table.name);

              table.columns = codeTable.lr_db_codecolumnsList.map((t) => ({
                name: t.f_DbColumnName,
                csType: t.f_CsType,
                isIdentity: t.f_IsIdentity == 1,
                isPrimary: t.f_IsPrimaryKey == 1,
                isNullable: t.f_IsNullable == 1,
                coment: t.f_Description,
              }));

              this.tableColumns[table.name] = table.columns;
            }
          }
        }
        //console.log("前端测试scheme.formInfo");
        //console.log(scheme.formInfo);
        this.$refs.formDesign.setData(scheme.formInfo);

        return true;
      } else {
        this.$message({
          message: "数据加载失败",
          type: "warning",
        });

        return false;
      }
    },

    //获取数据-表单提交
    getForm(isDraft) {
      let db = [];
      let rdb = [];
      let primaryKey = "";
      if (this.formData.f_FormType == 0) {
        // 普通表单
        const mainTable = this.dbTableData.find((t) => t.type == "main");

        const primaryKeyObj = mainTable.columns.find((t) => t.isPrimary);
        if (primaryKeyObj) {
          primaryKey = primaryKeyObj.name;
        }
      }

      const dbTableData = this.$deepClone(this.dbTableData);
      const dbTableRData = this.$deepClone(this.dbTableRData);

      for (const item of dbTableData) {
        if (this.formData.f_FormType == 0) {
          delete item.columns;
        }
        db.push(item);
      }
      for (const item of dbTableRData) {
        if (this.formData.f_FormType == 0) {
          delete item.columns;
        }
        rdb.push(item);
      }

      let scheme = {
        dbCode: this.formData.f_DbCode,
        db: db,
        rdb: rdb,
        primaryKey: primaryKey,
        formInfo: this.$refs.formDesign.getData(),
        formType: this.formData.f_FormType,
      };

      if (this.formData.f_FormType == 2) {
        scheme.primaryKey = this.$refs.apiOutput.getPrimary();
        scheme.output = this.$refs.apiOutput.getData();
        scheme.designDbTables = this.designDbTables || [];
      }

      let postData = {
        info: this.$deepClone({ ...this.formData, f_Type: isDraft ? 2 : 1 }),
        scheme: {
          F_Scheme: JSON.stringify(scheme),
          F_Type: isDraft ? 2 : 1,
        },
      };
      return postData;
    },

    handleFormTypeChange() {
      this.dbTableData = [];
      this.dbTableRData = [];
      this.$refs.formDesign.setFormType(this.formData.f_FormType);
      this.$emit("setFormType", this.formData.f_FormType);
    },

    addSqlData() {
      // 添加试图语句
      if (this.formData.f_DbCode) {
        this.editSql = false;
        this.sqlDialogTitle = "添加SQL";
        this.addSqlDialog = true;
      } else {
        this.$message({
          message: "请选择数据库",
          type: "warning",
        });
      }
    },
    editSqlData(row) {
      if (this.formData.f_DbCode) {
        this.editSql = true;
        this.sqlDialogRow = row;
        this.sqlDialogTitle = "编辑SQL";
        this.addSqlDialog = true;
      } else {
        this.$message({
          message: "请选择数据库",
          type: "warning",
        });
      }
    },
    deleteSqlData({ index, row }) {
      // 删除试图语句
      if (row.type != "main") {
        this.dbTableData.splice(index, 1);
      } else {
        this.$message({
          message: "主语句无法删除",
          type: "warning",
        });
      }
    },
    async sqlDialogSave(showLoading, hideLoading) {
      showLoading("保存中...");
      if (await this.$refs.sqlForm.validateForm()) {
        const data = this.$refs.sqlForm.getForm();
        if (this.dbTableData.length != 0 && data.type != "main") {
          if (data.sql.indexOf("@param") == -1) {
            this.$message({
              message: "请在语句中设置关联参数",
              type: "warning",
            });
            hideLoading();
            return;
          }
        }

        // 加载列字段
        const list = await this.$awaitWraper(apiScheme.geColnames(this.formData.f_DbCode, data.sql));
        if (list == null) {
          hideLoading();
          return;
        }
        data.columns = list.map((t) => {
          return { name: t };
        });

        if (this.editSql) {
          const index = this.dbTableData.findIndex((t) => (t.id = data.id));
          this.$set(this.dbTableData, index, data);
        } else {
          if (this.dbTableData.length == 0) {
            data.type = "main";
          } else {
            data.type = "chlid";
          }
          data.id = this.$uuid();
          this.dbTableData.push(data);
        }

        this.addSqlDialog = false;
      }

      hideLoading();
    },
    sqlDialogClosed() {
      this.$refs.sqlForm.resetForm();
    },
    sqlDialogOpened() {
      if (this.editSql) {
        this.$refs.sqlForm.setForm(this.sqlDialogRow);
      } else {
        this.$refs.sqlForm.resetSql();
      }
    },

    //新增接口-弹窗
    showApiForm() {
      this.apiDialog = true;
    },
    hideApiForm() {
      this.apiDialog = false;
    },
    childFormChange(e) {
      this.apiDialog = false;
      this.dialogTypeVisible = true;
      this.dialogApiData = e.row;
      //this.apiDataSet(e.row);
    },
    apiSelectChange(index) {
      this.dialogApiData.apiType = index;
      this.apiDataSet(this.dialogApiData);
      this.dialogTypeVisible = false;
    },
    checkOnlyDbTableData(row) {
      return this.dbTableData.some((item) => item.apiType === row.apiType);
    },
    checkNextAllDbTableData() {
      return this.dbTableData.length === 5;
    },

    apiDataSet(row) {
      this.apiDialog = false;

      if (this.checkOnlyDbTableData(row)) {
        this.$message({
          message: "添加的接口类型已重复",
          type: "warning",
        });
        return;
      }

      if (row.apiType === 1) {
        let responseType = JSON.parse(row.f_ResponseType);
        this.designDbTables = this.turnDesignDbTables(responseType);
      }

      this.dbTableData.push({
        ...row,
        id: row.f_Id,
        name: row.f_Name,
      });
    },
    turnDesignDbTables(responseType) {
      let mainDbTables = [];

      const mainData = responseType.propertysInfo.filter((item) => !item.propertysInfo.length);
      if (mainData.length) {
        //说明对象包含基本类型数据

        mainDbTables.push({
          id: "root",
          name: "root",
          comment: "root",
          type: "main",
          columns: mainData.map((item) => {
            return {
              name: item.propertyName.toLowerCase(),
              csType: null,
              isIdentity: false,
              isPrimary: false,
              isNullable: false,
              coment: "",
              value: "",
            };
          }),
        });
      }

      const childData = responseType.propertysInfo.filter((item) => item.propertysInfo.length);
      const childDbTables = childData.map((item) => {
        return {
          id: item.propertyName.toLowerCase(),
          name: item.propertyName.toLowerCase(),
          comment: item.propertyName.toLowerCase(),
          type: item.isArray ? "chlid" : "main",
          columns: item.propertysInfo.map((item) => {
            return {
              name: item.propertyName.toLowerCase(),
              csType: null,
              isIdentity: false,
              isPrimary: false,
              isNullable: false,
              coment: "",
              value: "",
            };
          }),
        };
      });

      return mainDbTables.concat(childDbTables);
    },
    deleteApiData({ index }) {
      this.dbTableData.splice(index, 1);
    },
  },
};
</script>
<style>
.ui-dialog-pop[data-center="true"] .l-dialog-btns {
  display: none;
}
.ui-dialog-pop .ui-dialog-TipText {
  padding: 40px 0;
  text-align: center;
}
.ui-dialog-pop .dialog-footer {
  text-align: center;
}
</style>
